package icu.cqcai.xinsi.config;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义认证入口点
 * 处理未授权访问，根据请求类型返回不同响应
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException authException) throws IOException, ServletException {
        
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        
        // 判断是否为API请求
        if (requestURI.startsWith("/api/") || requestURI.startsWith("/chat/")) {
            // API请求返回JSON格式的401错误
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"success\":false,\"message\":\"未授权访问，请先登录\",\"code\":401}");
        } else {
            // 页面请求重定向到登录页面，并带上原始请求URL
            String redirectURL = "/login";
            if (!"GET".equals(method)) {
                // 非GET请求直接跳转到登录页面
                response.sendRedirect(redirectURL);
            } else {
                // GET请求保存原始URL，登录后可以跳转回去
                String targetUrl = request.getRequestURL().toString();
                String queryString = request.getQueryString();
                if (queryString != null) {
                    targetUrl += "?" + queryString;
                }
                
                // 将目标URL作为参数传递给登录页面
                redirectURL += "?redirect=" + java.net.URLEncoder.encode(targetUrl, "UTF-8");
                response.sendRedirect(redirectURL);
            }
        }
    }
} 